import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/store/user'

import authRoutes from '@/router/routes/auth.js'
import blogRoutes from '@/router/routes/blog.js'
import aiProjectRoutes from '@/router/routes/ai-project.js'
import travelRoutes from '@/router/routes/travel.js'
import adminRoutes from '@/router/routes/admin.js'
import mainRoutes from '@/router/routes/main.js'
import foodRoutes from '@/router/routes/food.js'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    ...mainRoutes,
    ...authRoutes,
    ...blogRoutes,
    ...aiProjectRoutes,
    ...travelRoutes,
    ...adminRoutes,
    ...foodRoutes,
    // 404 页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/NotFound.vue')
    }
  ]
})

router.beforeEach(async (to, from, next) => {
  const userStore = useUserStore()
  
  // 需要认证的路由 (普通用户)
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!userStore.isLoggedIn) {
      return next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    }
    return next()
  }
  
  // 需要管理员权限的路由
  if (to.matched.some(record => record.meta.requiresAdmin)) {
    if (!userStore.isLoggedIn) {
      return next({
        path: '/admin/login',
        query: { redirect: to.fullPath }
      })
    }
    
    if (!userStore.isAdmin) {
      return next({
        path: '/',
        query: { from: to.path }
      })
    }
    return next()
  }
  
  // 需要访客状态的路由
  if (to.matched.some(record => record.meta.requiresGuest)) {
    if (userStore.isLoggedIn) {
      return next(userStore.isAdmin ? '/admin/dashboard' : '/')
    }
    return next()
  }
  
  next()
})

export default router